<?php


namespace app\api\controller;


use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\facade\Log;
use think\Response;

class CommonBase
{
    protected $modelName = "ApiBase";
    private $apikey = "32a1ff74699ff2d6ce4c497cb94cb5c8";
    protected $checkTokenOpen = true;

    public function __construct()
    {

        header("Access-Control-Allow-Credentials:true");
        header("Access-Control-Allow-Origin:*");//注意修改这里填写你的前端的域名
        header("Access-Control-Max-Age:3600");
        header("Access-Control-Allow-Headers:*,Content-Type,Fetch-Mode,accept,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,SessionToken,X-Token,Current-Admin-Id,Current-School-Id");
//        header("Access-Control-Allow-Headers:DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,SessionToken,X-Token");

        header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS, POIST');

        Log::record($_SERVER['REQUEST_METHOD'] . '  ' . getUrl(), 'info');
        Log::record('REFERER  ' .(array_key_exists('HTTP_REFERER',$_SERVER)?$_SERVER['HTTP_REFERER']:""), 'info');
        Log::record('GET  ' . json_encode($_GET, JSON_UNESCAPED_UNICODE), 'info');
        Log::record('POST  ' . json_encode($_POST, JSON_UNESCAPED_UNICODE), 'info');
        Log::record('cookie  ' . json_encode($_COOKIE, JSON_UNESCAPED_UNICODE), 'info');
        Log::record('input  ' . json_encode(input('param.'), JSON_UNESCAPED_UNICODE), 'info');

        if ($this->catchOptions()) {
            return $this->optionsReturn();
        }
    }

    //===处理跨域====
    protected function catchOptions()
    {

        $request = request();
//        var_dump( $request->method() == "OPTIONS");
        return $request->method() == "OPTIONS";
    }

    protected function optionsReturn()
    {
//        return Response::create(['test' => 'yckj'], 'json')->code(200);

//         return new HttpResponseException(Response::create(['test' => 'yckj'], 'json')->code(400));
        die("this is option");


    }


    //===end 处理跨域====





    protected function response($msg = "succ", $data = "")
    {
        $res['msg'] = $msg;
        if ($data == "") {
            $res['data'] = new \stdClass();
        } else {
            $res['data'] = $data;
        }
        $code = 0;
        $res['code'] = $code;
        Log::record("ouput:data:" . mb_strstr(json_encode($res, JSON_UNESCAPED_UNICODE), 0, 1000) . ",code:" . $code, "debug");
        //JSON
        header('Content-type: application/json');
        return json($res, $code);
    }





    public function success($data,$msg=""){
        throw new HttpResponseException(Response::create(returnFormat(0,$msg,$data),"json"));
    }

    public function error($msg,$code=999){
        throw new HttpResponseException(Response::create(returnFormat($code,$msg),"json"));
    }

    /**
     * 自动校验
     * @param $class
     * @param $param
     */
    public function autoValid($class,$param){
        try {
            validate($class)->check($param);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            $this->error($e->getError());
        }
    }

    /**
     * 接口签名校验
     */
    public function checkApiSign(){
        $param = request()->param();

        $this->autoValid([
            "timestamp"=>"require",
            "sign"=>"require",
        ], $param);
        if(!($param["timestamp"]>=time()-2*60 && $param["timestamp"]<=time()+2*60)){
            $this->error("时间戳不合法，请刷新");
        }
        $sign=$param["sign"];
        unset($param["sign"]);
        ksort($param);
        $secret=config("common.api_sign_secret");

        $sign2=md5(json_encode($param,JSON_UNESCAPED_UNICODE).$secret);
//        print_r([
//            "sign_str"=>json_encode($param,JSON_UNESCAPED_UNICODE).$secret,
//            "sign2"=>$sign2,
//        ]);exit;
        if($sign!==$sign2){
            $this->error("签名错误");
        }
    }
}
